package cn.deschen.eshop.auth.validate.image;

import cn.deschen.eshop.auth.properties.ImageCodeProperties;
import cn.deschen.eshop.auth.properties.SecurityProperties;
import cn.deschen.eshop.auth.validate.ValidateCode;
import cn.deschen.eshop.auth.validate.ValidateCodeGenerator;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * @Author hanbin_chen
 * @Description 图片验证码生成器
 * @DateTime 2021/1/15 16:02
 * @Version V1.0.0
 */
@Component
@ConditionalOnClass(value = ImageValidateCodeGenerator.class)
public class ImageValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public ValidateCode generate(ServletWebRequest request) {
        // 获取图片验证码属性
        ImageCodeProperties imageCodeProperties = securityProperties.getCode().getImage();
        String height = ServletRequestUtils.getStringParameter(request.getRequest(), imageCodeProperties.getReqHeightKey(),
                imageCodeProperties.getHeight());
        String width = ServletRequestUtils.getStringParameter(request.getRequest(), imageCodeProperties.getReqWidthKey(),
                imageCodeProperties.getWidth());
        String length = ServletRequestUtils.getStringParameter(request.getRequest(), imageCodeProperties.getReqLengthKey(),
                imageCodeProperties.getLength());
        // 根据属性生成图片验证码
        DefaultKaptcha defaultKaptcha = defaultKaptcha(height, width, length);
        String code = defaultKaptcha.createText();
        BufferedImage image = defaultKaptcha.createImage(code);
        return new ImageValidateCode(code, image);

    }


    /**
     * 获取defaultKaptcha实体类,用于验证码生成处理
     *
     * @param height 图片高度
     * @param width 图片宽度
     * @param length 图片长度
     * @return
     */
    public DefaultKaptcha defaultKaptcha(String height, String width, String length) {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        // 图片宽
        properties.setProperty("kaptcha.image.width", width);
        // 图片高
        properties.setProperty("kaptcha.image.height", height);
        // 验证码长度
        properties.setProperty("kaptcha.textproducer.char.length", length);
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);

        return defaultKaptcha;
    }

}
